package users

import (
	"power/core/common/errorcode"
	"power/core/dao/table"
	"power/core/dao/userdao"
	"power/core/localwrap"

	"github.com/RocksonZeta/wrap/errs"
	"github.com/RocksonZeta/wrap/utils/hashutil"
)

var logUserPrivates = localwrap.GetLogger().Fork("power/core/service/users", "UserPrivates")

type UserPrivates struct{}

func (s UserPrivates) Query(param userdao.UserPrivatesQueryParam) ([]table.UserPrivate, int64) {
	logUserPrivates.Debug().Func("Query").Interface("param", param).Send()
	d := localwrap.GetRedisedMysql()
	defer d.Close()
	return userdao.UserPrivates{RedisedMysql: d}.Query(param)
}

func (s UserPrivates) Get(id int) table.UserPrivate {
	logUserPrivates.Debug().Func("Get").Int("id", id).Send()
	d := localwrap.GetRedisedMysql()
	defer d.Close()
	return userdao.UserPrivates{RedisedMysql: d}.Get(id)
}

func (s UserPrivates) Add(param userdao.UserPrivatesAddParam) table.UserPrivate {
	logUserPrivates.Debug().Func("Add").Interface("param", param).Send()
	d := localwrap.GetRedisedMysql()
	defer d.Close()
	return userdao.UserPrivates{RedisedMysql: d}.Add(param)
}

func (s UserPrivates) Update(param userdao.UserPrivatesUpdateParam) {
	logUserPrivates.Debug().Func("Update").Interface("param", param).Send()
	d := localwrap.GetRedisedMysql()
	defer d.Close()
	userdao.UserPrivates{RedisedMysql: d}.Update(param)
}

func (s UserPrivates) Delete(id int) {
	logUserPrivates.Debug().Func("Delete").Int("id", id).Send()
	d := localwrap.GetRedisedMysql()
	defer d.Close()
	userdao.UserPrivates{RedisedMysql: d}.Delete(id)
}

//GetByUid
func (s UserPrivates) GetByUid(uid int) table.UserPrivate {
	logUserPrivates.Debug().Func("GetByUid").Int("uid", uid).Send()
	d := localwrap.GetRedisedMysql()
	defer d.Close()
	return userdao.UserPrivates{RedisedMysql: d}.GetByUid(uid)
}

type SigninParam struct {
	Email    string
	Password string
}

func (s UserPrivates) Signin(param SigninParam) (table.UserPrivate, *errs.Err) {
	logUserPrivates.Debug().Func("Signin").Interface("param", param).Send()
	d := localwrap.GetRedisedMysql()
	defer d.Close()
	r := userdao.UserPrivates{RedisedMysql: d}.GetByEmail(param.Email)
	if r.Id == 0 {
		return r, errs.NewUserError(errorcode.UserEmailNotExists, "email not exists.")
	}
	if r.Password != Password(param.Password) {
		return r, errs.NewUserError(errorcode.UserPasswordError, "signin password error.")
	}
	return r, nil
}

func Password(str string) string {
	return hashutil.Md5(hashutil.Md5(str))
}
